<template>
  <div class="chart-container">
    <div ref="chart" class="chart-inner"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { onMounted, ref, watch, onUnmounted } from 'vue';

export default {
  name: 'ProductPurchaseRanking',
  props: {
    chartData: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const chart = ref(null);
    let myChart = null;

    const initChart = () => {
      if (!chart.value) return;
      
      if (myChart) {
        myChart.dispose();
      }
      
      myChart = echarts.init(chart.value);
      
      // 直接使用后端返回的聚合数据，按购买次数降序排列
      const sortedData = [...props.chartData]
        .sort((a, b) => a.cnt - b.cnt) // 降序排列
        .slice(0, 10); // 取前10名
      
      const yAxisData = sortedData.map(item => `商品${item.itemId}`);
      const xAxisData = sortedData.map(item => item.cnt);
      
      const { offsetWidth } = chart.value;
      
      const option = {
        title: {
          text: '商品购买排名 Top 10',
          left: 'center',
          textStyle: {
            fontSize: 20
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}：购买了{c}次',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              title: '保存图片',
              type: 'png'
            }
          },
          right: 10,
          top: 5
        },
        grid: {
          left: offsetWidth < 600 ? '15%' : '10%',
          right: offsetWidth < 600 ? '15%' : '8%',
          bottom: '5%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '购买次数',
          min: 0,
          axisLabel: {
            formatter: '{value}次'
          }
        },
        yAxis: {
          type: 'category',
          data: yAxisData,
          name: '商品ID',
          axisLabel: {
            fontSize: offsetWidth < 600 ? 10 : 12,
            formatter: (value) => {
              // 如果商品ID显示太长，可以适当截断
              return value.length > 15 ? value.substring(0, 12) + '...' : value;
            }
          }
        },
        series: [{
          type: 'bar',
          data: xAxisData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#91cc75' },
              { offset: 0.5, color: '#73bf60' },
              { offset: 1, color: '#5470c6' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#5470c6' },
                { offset: 0.7, color: '#73bf60' },
                { offset: 1, color: '#91cc75' }
              ])
            }
          },
          label: {
            show: true,
            position: 'right',
            formatter: '{c}次',
            fontSize: 12,
            distance: 5
          },
          barCategoryGap: '20%'
        }]
      };
      
      myChart.setOption(option);
    };

    const handleResize = () => {
      if (myChart) {
        myChart.resize();
      }
    };

    onMounted(() => {
      setTimeout(initChart, 100);
      window.addEventListener('resize', handleResize);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      if (myChart) {
        myChart.dispose();
      }
    });

    // 监听数据变化重新渲染图表
    watch(() => props.chartData, () => {
      if (myChart) {
        setTimeout(initChart, 50);
      }
    }, { deep: true });

    return {
      chart
    };
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  background-color: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.chart-inner {
  width: 100%;
  height: 100%;
}
</style>